$(window).ready(function() {
    var request = GetRequest();
    /*查看分类效果*/
    /*-------*/
    $("#Pagination").pagination("100");
    /*  删除此行 */
    /*------*/
    /*---详细选择框--*/
    //-------------------------


    $.ajax({
        url: "/index/getMenu",
        type: 'get',
        async: false,
        success: function (data) {

            var data = data.data;
            if (data != null) {

                var z = 0;//用来转化成数字的中介
                // 导航栏Collections的下拉导航
                var collectionNav_li = "";
                //搜索框左边的分类
                var collectionOpt = "";
                for (var d in data) {
                    collectionNav_li += "<li> <a href=\"/collection.html?keyword=&categoryId=" + data[d].id + "\" class=\"site-nav__link\">" + data[d].name + "</a> </li>";
                    collectionOpt += '<option value="' + data[d].id + '">' + data[d].name + '</option>';
                }
                $("#collectionNav").append(collectionNav_li);
                $("#collection-option").append(collectionOpt);


                //导航栏下的最上面
                //先加home的
                // var collectionQue_li = `<li class="active">
					// 			<a href="#All" data-toggle="tab" aria-expanded="true">
					// 				所有产品
					// 			</a>
					// 		</li>`;
                //点击后转换的块
                // var home = ``;

                // home += `<div class="tab-pane fade active in" id="All">
					// 			<!-- 类似淘宝的分类 -->
					// 			<div class="detail_informationTop ">
					// 				<p>所有分类 &gt;</p>
					// 				<span class="detaInfor_PackUp" style=""><a href="javascript:;">收起分类</a></span>
					// 			</div>
					// 			<div class="detail_informationContent">
					// 				<div class="detail_informationContentT">
					// 					<ul class="select" style="list-style: none; display: block;">`;
                // //转换的块添加子类
                // z = 0;
                // for (var t in data) {
                //     z = parseInt(t) + 1;
                //     home += `<li class="select-list">
                //                     <dl id="select` + z + `">
                //                         <dt>` + data[t].name + `</dt>
                //                         <dd class="select-all selected"><a href="#">全部</a></dd>
                //                    `;
                //     var childs = data[t].children;
                //     for (var x in childs) {
                //         home += `<dd><a href="javascript:;">` + childs[x].name + `</a></dd>`;
                //     }
                //     home += ` </dl>
                //                 </li>`;
                // }
                // home += `<li class="select-result">
					// 							<dl id="select0">
					// 								<dt>已选条件：</dt>
					// 								<dd class="select-no">暂时没有选择过滤条件</dd>
					// 							</dl>
					// 						</li>
					// 					</ul>
					// 					<!-- -================正在制作   selected 是背景橙色那个 -->
					// 				</div>
					// 			</div>
					// 		</div>`;

                var collectionQue_li ="";
                var collectionQue_div = "";
                var flag=1,flag_2=1;
                for (var d in data) {


                    for(var t=0;t< data[d].children.length&&flag==1;t++) {
                        if (request.id == data[d].children[t].id) {
                            collectionQue_li += `<li class="active"><a href="#` + data[d].name + `" data-toggle="tab" aria-expanded="false">` + data[d].name + `</a></li>`;
                            collectionQue_div += `<div class="tab-pane fade active in" id="` + data[d].name + `">
                                        <div class="detail_informationTop">`;
                           flag=0;flag_2=0;
                        }
                    }
                    if(flag_2==1) {
                        collectionQue_li += `<li class=""><a href="#` + data[d].name + `" data-toggle="tab" aria-expanded="false">` + data[d].name + `</a></li>`;
                        collectionQue_div += `<div class="tab-pane fade" id="` + data[d].name + `">
                                        <div class="detail_informationTop">`;
                    }
                    flag_2=1;
                    $.ajax({
                        url: "/product/getAncestorsByCategoryId?categoryId="+data[d].id,//+categoryId,
                        type: 'get',
                        async: false,
                        success: function (data) {
                            //得到的是list
                            var grade="";
                            for(var k in data){
                                //从第一级开始,所以得从后面拿
                                if(data[k]==0)
                                    data[k]='';
                                grade=`<p><a href="/collection.html?keyword=&categoryId=`+data[k]+`">`+ k+` &gt;</a></p>`+grade;   //加在后面
                            }
                            collectionQue_div=collectionQue_div+grade;
                        }
                    });

                    collectionQue_div +=`<span class="detaInfor_PackUp" style=""><a href="javascript:;">收起分类</a></span>
								    </div>
								<div class="detail_informationContent">
									<div class="detail_informationContentT">
										<ul class="select" style="list-style: none; display: block;" id="` + data[d].name + `">`;

                    //转换的块添加子类
                    var childs = data[d].children;
                    z = 0;
                    for (var t in childs) {
                        z = parseInt(t) + 1;
                        collectionQue_div += `<li class="select-list">
                                    <dl id="select` + z + `">
                                        <dt><a href="/agriecomIndex/search/forward?keyword=&categoryId=`+childs[t].id+`">` + childs[t].name + `</a></dt>
                                     
                                   `;
                        var grandsons = childs[t].children;
                        for (var x in grandsons) {
                            collectionQue_div += `<dd><a href="/agriecomIndex/search/paramForward?categoryId=`+grandsons[x].id+`">` + grandsons[x].name + `</a></dd>`;
                        }
                        collectionQue_div += ` </dl>
                                </li>`;
                    }

                    collectionQue_div += `
										</ul>
										<!-- -================正在制作   selected 是背景橙色那个 -->
									</div>
								</div>
							</div>`;
                }

                $("ul#myTab").append(collectionQue_li);
                $("div#myTabContent").append( "" + collectionQue_div);

                //--------------------------------

                //
                // let judgeTextFn = (ele) => {
                //     if ($(ele).children("dl").children("dd").text() === "") {
                //         $(ele).children("dl").children("dd").text("暂时没有选择过滤条件");
                //     }
                // };
                // let {entries} = Object;
                // let newdd1;
                // let IdCheck = {};          //*** 里面有动态代码
                // z = 0;
                // for (let i in data) {
                //     z = parseInt(i) + 1;
                //     IdCheck["select" + z] = 'select' + i + '0';
                // }
                //
                //
                // let removeChildFn = (ele, fDom, clickIndex) => {
                //     setTimeout(() => {
                //         $(ele).eq(0).find(fDom).each((index, ele) => {
                //             $(ele).on('click', () => {
                //                 for (let [key, value] of entries(IdCheck)) {
                //                     if ($(ele).attr('id') === value) {
                //                         $('dl#' + key).eq(clickIndex).find('dd.selected').removeClass('selected').siblings('dd.select-all').addClass('selected');
                //                     }
                //                 }
                //                 $(ele).remove();
                //                 judgeTextFn("#home .select-result");
                //                 judgeTextFn("#ios .select-result");
                //                 judgeTextFn("#jmeter .select-result");
                //                 judgeTextFn("#All .select-result");
                //                 for (var d in data) {
                //                     judgeTextFn("#" + data[d].name + " .select-result");
                //                 }
                //
                //                 //---------------测试返回原来的位置-------------------
                //             });
                //
                //         });
                //     }, 5);
                //
                //
                // };      //*** 里面有动态代码
                // let ddClickFn = (ele, childDom, selectClass, value, index) => {
                //     $(ele).children(childDom).click(function () {
                //         $(this).addClass("selected").siblings().removeClass("selected");
                //         if ($(this).hasClass("selected") === true) {
                //             newdd1 = $($(this)).clone();
                //             removeChildFn(selectClass, newdd1[0], index);
                //             if ($(selectClass).children("dl").children("dd").text() === "暂时没有选择过滤条件") {
                //                 $(selectClass).children("dl").children("dd").text("").parent().append(newdd1.attr("id", value));
                //             }
                //             if ($(this).hasClass("select-all") === true) {
                //                 $(selectClass).children("dl").children("#" + value).remove();
                //                 if ($(selectClass).children("dl").children("dd").text() === "") {
                //                     $(selectClass).children("dl").children("dd").text("暂时没有选择过滤条件");
                //                 }
                //             }
                //             if ($(this).hasClass("select-all") === false && $(selectClass).children("dl").children("#" + value) != null) {
                //                 $(selectClass).children("dl").children("#" + value).remove();
                //                 $(selectClass).children("dl").append(newdd1.attr("id", value));
                //             }
                //         }
                //     });
                //
                // }
                // setTimeout(() => {
                //     $(".detaInfor_PackUp").click(function () {
                //         $(".detaInfor_PackUp").effect('slide', 500);
                //         // $(".select").hide(500);
                //         if ($(".select").css("display") != "none") {
                //             $(".select").hide(500);
                //         }
                //         else {
                //             $(".select").effect("slide", 800);
                //         }
                //     });
                //     //全部分类的要先加上
                //     z = 0;
                //     for (var d in data) {
                //         z = parseInt(d) + 1;
                //         ddClickFn("#All #select" + z, "dd", "#All .select-result", IdCheck["select" + z], 0);
                //         for (var t in data[d].children) {
                //             var x = parseInt(t) + 1;
                //             ddClickFn("#" + data[d].name + " #select" + x, "dd", "#" + data[d].name + " .select-result", IdCheck["select" + x], z);
                //         }
                //
                //     }
                // }, 0);                       //*** 里面有动态代码


                // //点击后消失
                // var ResultDl = document.getElementById('select0');
                // var ddArr = ResultDl.children;


                //---------------------------------
                //点击文字改变   收起分类
                $('span.detaInfor_PackUp').each((index, ele) => {
                    $(ele).on('click', () => {
                        if ($('div.detail_informationContentT').children('ul').css('display') === 'block') {
                            $(ele).children('a').text('展开分类');
                        } else {
                            $(ele).children('a').text('收起分类');
                        }
                    });
                });

            }

        }



    });

    //获取路径中的参数
    function GetRequest() {
        var url = location.search;         //获取url中"?"符后的字串
        var theRequest = new Object();
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            var strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
            }
        }
        return theRequest;
    }

/*-------------------------------------------------------------*/
//获取全局数据
    $.getUrlParam = function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }
    let categoryId = $.getUrlParam('categoryId');
    let keyword=$.getUrlParam('keyword');
    let length =3;  //每页显示条数
    let page=1;     //默认第一页

    let ajaxFun=function (categoryId,keyword,page,length){
        var url;
        if(keyword==null){
            url="/agriecomIndex/search/getProByParentId?categoryId="+categoryId+"&page="+page+"&limit="+length;
        }else
            url="/agriecomIndex/search/categoryAndKeyword?categoryId="+categoryId+"&keyword="+keyword+"&page="+page+"&limit="+length;
        $.ajax({
            url: url,
            dataType: "json",
            type: "GET",
            success: function (data) {
                if(data.count<=length){     //不分页
                    $(".pages").remove();
                }else{

                    $("#Pagination").pagination(data.count, {
                        num_edge_entries: 1, //边缘页数
                        num_display_entries: 3, //主体页数
                        callback: pageselectCallback,
                        items_per_page: length, //每页显示1项
                        current_page:page-1,
                        prev_text: "前一页",
                        next_text: "后一页"
                    });
                    /*
                    *       GO页面跳转
                    */
                    $(".searchPage a").bind("click",function(){
                        window.location="/agriecomIndex/search/forward?categoryId="+categoryId+"&keyword="+keyword;
                    });


                    let countPage=data.count%length==0?data.count/length:parseInt(data.count/length)+1;
                    $(".page-sum strong").html(countPage);
                    $(".page-go input").focusout(function(){
                        let desPage=$(".page-go input").val();
                        if (desPage <= countPage &&desPage!=""&&desPage>0) {
                            $(".searchPage a").unbind('click');
                            $(".searchPage a").bind('click',function(){
                                var childDiv=$(".grid-uniform-category>div:first-child").clone(false,true);
                                parentDiv.html("");
                                parentDiv.append(childDiv);
                                if(keyword==null)
                                    ajaxFun(categoryId, null, desPage, length);
                                else
                                    ajaxFun(categoryId, keyword, desPage, length);
                            });
                        }
                    })
                    function pageselectCallback(page_index, jq){
                        let childDiv=$(".grid-uniform-category>div:first-child").clone(false,true);
                        parentDiv.html("");
                        parentDiv.append(childDiv);
                        ajaxFun(categoryId,keyword,page_index+1,length);
                        return false;
                    }

                }
                var parentDiv=$(".grid-uniform-category");
                $.each(data.data,function(i,ele){
                    //回显
                    var imgDiv=$(".product-image")[i];
                    $(imgDiv.children[0]).attr("href",ele.produceId);
                    $(imgDiv.children[0].children[0]).attr("src",ele.produceImg);
                    var num=i+1;

                    //star
                    $($(".grid-uniform-category>div:nth-child("+num+")>div>div")[1]).remove();
                    $($(".grid-uniform-category>div:nth-child("+num+")>div>div")[0]).after(`<div class="rating-star">
														<span class="spr-badge" id="spr_badge_3008529987" data-rating="0.0">
															<span class="spr-starrating spr-badge-starrating">
																
															</span>
															<span class="spr-badge-caption"> </span>
														</span>
                                    </div>`);

                    //产品名
                    $($(".grid-uniform-category>div:nth-child("+num+")>div>p")[0]).html("");
                    $($(".grid-uniform-category>div:nth-child("+num+")>div>p")[0]).html("<a href='"+ele.produceId+"'>"+ele.produceName+"</a>");
                    //价格
                    var oldPrice=parseFloat(ele.price)+18;
                    $($(".grid-uniform-category>div:nth-child("+num+")>div>p")[1]).html("");
                    $($(".grid-uniform-category>div:nth-child("+num+")>div>p")[1]).html("<strong>On Sale</strong>" +
                        "<span class=\"money\" data-currency-usd=\"$19.99\">"+ele.price+ele.unit+"</span>" +
                        "<span class=\"visually-hidden\">Regular price</span>" +
                        "<s><span class=\"money\" data-currency-usd=\"$24.99\">"+oldPrice+ele.unit+"</span></s>");
                    //排列方式切换（商品简介）
                    $($(".list-mode-description")[i]).html("");
                    $($(".list-mode-description")[i]).html(ele.produceBrief);
                    //联系商家

                    $($(".add-to-cart-form form div")[i]).html("");
                    $($(".add-to-cart-form form div")[i]).html('<a href="/product.html?id='+ele.produceId+'" class="btn btn-1 add-to-cart" title="call now">\n' +
                        '                                                        <i class="fa fa-shopping-cart"></i>联系商家</span>\n' +
                        '                                                    </a>');

                    //拼接
                    var childDiv=$(".grid-uniform-category>div:first-child").clone(false,true);
                    parentDiv.append(childDiv);
                    starChange('span#spr_badge_3008529987',ele.remarks,i);
                })
                $(".grid-uniform-category>div:last-child").empty();
            }
        });
    }
    ajaxFun(categoryId,keyword,page,length);


})
let starChange = (str,n=2,index=0)=>{
    let temp = `<i class="spr-icon spr-icon-star" style=""></i>`;
    for(let i=0;i<n;i++){
        $(str).eq(index).find('span.spr-starrating.spr-badge-starrating').append(temp);
    }
}